﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;

using Kannon.Core;

namespace Kannon.Integration.Iis
{
    public class KannonHttpHandlerFactory : IHttpHandlerFactory
    {
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            //
            // This is woefully suboptimal, but will do for now
            var applicationBase = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
            var applicationType =
                (from assembly in Directory.GetFiles(applicationBase, "*.dll").Select(f => Assembly.LoadFrom(f))
                 from type in assembly.GetExportedTypes()
                 where typeof(KannonApplication).IsAssignableFrom(type) && !type.IsAbstract
                 select type).FirstOrDefault();

            return new KannonHttpHandler(applicationType);
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
        }
    }
}
